package cn.edu.sdjzu.xg.eagle.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 工厂模式dao
 * 没有实现单例
 */
public class DaoFactory {
    private static final String daoPackageName = "cn.edu.sdjzu.xg.eagle.dao.mapper";
    private static final Logger LOGGER = LoggerFactory.getLogger(DaoFactory.class);
    // 隐藏构造器，因为这个类只包含静态方法
    private DaoFactory() {}

    /**
     * 泛型方法，获取 DAO 接口类型的实现类对象
     * @param daoInterface
     * @param daoClassName
     * @return
     * @param <T>
     * @throws RuntimeException 调用者无须处理异常
     */
    public static <T> T getDao(Class<T> daoInterface, String daoClassName) throws RuntimeException {
        try {
            Class<?> clazz = Class.forName(daoPackageName + "." + daoClassName);
            if (!daoInterface.isAssignableFrom(clazz)) {
                throw new RuntimeException("类 " + daoPackageName + " 没有实现接口 " + daoInterface.getName());
            }
            return (T) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("在包 " + daoPackageName + " 中找不到DAO类 " + daoPackageName, e);
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException("在实例化DAO类 " + daoPackageName + " 时发生错误", e);
        }
    }
}
